<template>
  <div class="work-order-completed page-container">
    <div class="page-header">
      <h2>已办查询</h2>
      <div>
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="danger" @click="handleDeleteSelected" :disabled="selectedRows.length === 0" style="margin-left: 10px;">
          删除
        </el-button>
        <el-button type="success" @click="exportToCSV" style="margin-left: 10px;">
          导出CSV
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable style="width: 120px">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
            <el-option label="紧急" value="urgent" />
          </el-select>
        </el-form-item>
        <el-form-item label="完成时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工单列表 -->
    <el-card>
      <el-table
        :data="workOrders"
        v-loading="loading"
        stripe
        @row-click="viewDetail"
        @selection-change="handleSelectionChange"
        style="cursor: pointer"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="order_number" label="工单号" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator_name" label="创建人" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="160" />
        <el-table-column prop="completed_at" label="完成时间" width="160" />
        <el-table-column prop="duration" label="处理时长" width="120">
          <template #default="{ row }">
            {{ calculateDuration(row.created_at, row.completed_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="viewDetail(row)">
              查看详情
            </el-button>
            <el-button type="info" size="small" @click.stop="exportRecord(row)">
              导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { workOrdersApi } from '@/api'

const router = useRouter()

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const selectedRows = ref([])

const searchForm = reactive({
  status: '',
  priority: '',
  dateRange: null as [string, string] | null
})

const workOrders = ref([])

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    completed: 'success',
    cancelled: 'warning'
  }
  return typeMap[status] || undefined
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || status
}

const getPriorityType = (priority: string) => {
  const typeMap: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    urgent: 'danger'
  }
  return typeMap[priority] || undefined
}

const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return textMap[priority] || priority
}

const calculateDuration = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) return '-'
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  const diffMs = end.getTime() - start.getTime()
  
  const hours = Math.floor(diffMs / (1000 * 60 * 60))
  const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

const loadWorkOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      per_page: pageSize.value,
      status: searchForm.status || 'completed,cancelled',
      priority: searchForm.priority,
      start_date: searchForm.dateRange?.[0],
      end_date: searchForm.dateRange?.[1],
      show_all: true
    }

    const response = await workOrdersApi.getWorkOrders(params)
    workOrders.value = response.data.work_orders || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('加载已办工单失败:', error)
    ElMessage.error('加载已办工单失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadWorkOrders()
}

const resetSearch = () => {
  searchForm.status = ''
  searchForm.priority = ''
  searchForm.dateRange = null
  currentPage.value = 1
  loadWorkOrders()
}

const refreshData = () => {
  loadWorkOrders()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadWorkOrders()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadWorkOrders()
}

const viewDetail = (row: any) => {
  router.push(`/work-orders/${row.id}`)
}

const exportRecord = (row: any) => {
  ElMessage.info('导出功能开发中...')
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleDeleteSelected = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的工单')
    return
  }
  ElMessageBox.confirm(
    `确认删除选中的 ${selectedRows.value.length} 个工单吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      for (const order of selectedRows.value) {
        await workOrdersApi.deleteWorkOrder(order.id)
      }
      ElMessage.success('删除成功')
      refreshData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const exportToCSV = () => {
  if (workOrders.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  const headers = ['工单号', '标题', '状态', '优先级', '创建人', '负责人', '创建时间']
  const csvRows = [headers.join(',')]
  workOrders.value.forEach(order => {
    const row = [
      order.order_number,
      order.title || '',
      order.status || '',
      order.priority || '',
      order.creator_name || '',
      order.assignee_name || '',
      order.created_at || ''
    ]
    const escapedRow = row.map(field => {
      if (typeof field === 'string' && (field.includes(',') || field.includes('"'))) {
        return `"${field.replace(/"/g, '""')}"`
      }
      return field
    })
    csvRows.push(escapedRow.join(','))
  })
  const csvString = csvRows.join('\n')
  const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'work_orders_completed.csv'
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

onMounted(() => {
  loadWorkOrders()
})
</script>

<style scoped>
.work-order-completed {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.page-container {
  padding: 20px;
}
</style>
